package org.example.shop_front_api.service;

import org.example.shop_front_api.entity.Address;
import org.example.shop_front_api.mapper.AddressMapper;
import org.example.shop_front_api.utils.JsonResult;
import org.example.shop_front_api.utils.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class AddressService {
    @Autowired
    private AddressMapper addressMapper;

    public JsonResult addAddress(Address address) {
        Long userId = UserContext.getUser().getId();
        address.setUserId(userId);
        if (address.getIsDefault() == 1) {
            addressMapper.clearDefaultByUserId(userId);
        }
        address.setCreateTime(LocalDateTime.now());
        address.setUpdateTime(LocalDateTime.now());
        int result = addressMapper.addAddress(address);
        return result > 0 ? JsonResult.success("添加成功", address) : JsonResult.failed("添加失败");
    }

    public JsonResult listByUserId(Long userId) {
        List<Address> addressList = addressMapper.listByUserId(userId);
        return JsonResult.success("查询地址列表成功", addressList);
    }

    public JsonResult getById(Long id) {
        Address address = addressMapper.getById(id);
        if (address == null || !address.getUserId().equals(UserContext.getUser().getId())) {
            return JsonResult.failed(404, "地址不存在或无权限操作");
        }
        return JsonResult.success("查询地址详情成功", address);
    }

    public JsonResult updateAddress(Address address) {
        Address dbAddress = addressMapper.getById(address.getId());
        if (dbAddress == null || !dbAddress.getUserId().equals(UserContext.getUser().getId())) {
            return JsonResult.failed(404, "地址不存在或无权限操作");
        }
        if (address.getIsDefault() == 1) {
            addressMapper.clearDefaultByUserId(UserContext.getUser().getId());
        }
        address.setUpdateTime(LocalDateTime.now());
        addressMapper.updateAddress(address);
        return JsonResult.success("更新地址成功", address);
    }

    public JsonResult deleteAddress(Long id) {
        Address address = addressMapper.getById(id);
        if (address == null || !address.getUserId().equals(UserContext.getUser().getId())) {
            return JsonResult.failed(404, "地址不存在或无权限操作");
        }
        if (address.getIsDefault() == 1) {
            return JsonResult.failed(400, "默认地址不能删除");
        }
        addressMapper.deleteAddress(id);
        return JsonResult.success("删除地址成功");
    }
}